# Copyright (c) 2025, EAM Team and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document
from frappe.utils import add_days, today


class EquipmentMaintenancePlan(Document):
    def autoname(self):
        """自动生成计划编号"""
        from frappe.utils import now_datetime
        now = now_datetime()
        year = now.year
        
        # 获取当年的序号
        count = frappe.db.count("Equipment Maintenance Plan", 
                               filters={"creation": [">=", f"{year}-01-01"]}) + 1
        
        self.plan_id = f"MP-{year}-{count:05d}"
        self.name = self.plan_id

    def validate(self):
        """计算下次执行日期"""
        if self.start_date and self.frequency_days:
            if not self.next_execution_date:
                self.next_execution_date = add_days(self.start_date, self.frequency_days)

    def on_submit(self):
        """提交保养计划"""
        self.status = "启用"
        self.save()

    def schedule_next_maintenance(self):
        """安排下次保养"""
        if self.next_execution_date and self.next_execution_date <= today():
            # 创建保养任务
            maintenance = frappe.get_doc({
                "doctype": "Equipment Maintenance",
                "equipment": self.equipment,
                "maintenance_type": "预防性维护",
                "scheduled_date": self.next_execution_date,
                "assigned_technician": self.responsible_person,
                "description": f"按计划执行{self.plan_name}",
                "maintenance_plan": self.name,
                "status": "计划中"
            })
            maintenance.insert()
            
            # 更新执行记录
            self.execution_count = (self.execution_count or 0) + 1
            self.last_execution_date = self.next_execution_date
            self.next_execution_date = add_days(self.next_execution_date, self.frequency_days)
            self.save()
            
            frappe.msgprint(f"已创建保养任务: {maintenance.name}")
            
            return maintenance.name

    def pause_plan(self):
        """暂停计划"""
        self.status = "暂停"
        self.save()

    def resume_plan(self):
        """恢复计划"""
        self.status = "启用"
        # 重新计算下次执行日期
        if self.last_execution_date:
            self.next_execution_date = add_days(self.last_execution_date, self.frequency_days)
        else:
            self.next_execution_date = add_days(today(), self.frequency_days)
        self.save()

    def stop_plan(self):
        """停用计划"""
        self.status = "停用"
        self.save()

    def update_cost(self, cost):
        """更新累计成本"""
        self.total_cost = (self.total_cost or 0) + cost
        self.save()

    def get_overdue_days(self):
        """获取逾期天数"""
        if self.next_execution_date and self.next_execution_date < today():
            from frappe.utils import date_diff
            return date_diff(today(), self.next_execution_date)
        return 0